#include "utils.h"
#include<iostream>
#include<cstdlib>
#include<assert.h>
#include<string>
#include<ctime>
#include <sys/epoll.h>

class clientChat{
    char ipstr[16];
    int port;
    struct sockaddr_in dest;
    char uname[8];
    int m_epfd;
    int dfd;
    socklen_t slen;
    struct epoll_event m_evs[1024];
    public:
    clientChat(const char *ip,int port){
        strncpy(this->ipstr,ip,16);
        this->port = port;
        printf("%s\n",ipstr);
    }
    void start(){
    dfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == dfd)
    {   printf("%s\n","socket创建失败");
		return;
    }
 

    memset(&dest, 0, sizeof(struct sockaddr_in));
 
    dest.sin_family = AF_INET;
    dest.sin_port = htons(port);
    dest.sin_addr.s_addr = inet_addr((char*)ipstr);
    slen = sizeof(dest);
    memset(uname,0x00,8);
    if(connect(dfd, (struct sockaddr *)&dest, sizeof(dest)) < 0)
    {
    perror("bind");
    close(dfd);
        return ;
    }
    printf("%s\n","请输入用户名");
    if(fgets(uname,8,stdin)!=NULL){
        for(int i=0;i<8;++i){
            if(uname[i]=='\n'){
                uname[i]='\0';
            }
        }
        printf("%s\n","用户信息已配置");
    }

    }


    void ToALL(const char * msg){
        message mg;
        strncpy(mg.fname,uname,7);
        memset(mg.tname,0x00,8);
        strncpy(mg.m_msg,msg,strlen(msg));
        sendto(dfd,(char*)&mg,sizeof(mg),0,(struct sockaddr*)&dest,slen);
        printf("%s\n","广播结束");


    }
    void ToOne(const char*tname,const char* msg){
        message mg;
        strncpy(mg.fname,uname,7);
        strncpy(mg.tname,tname,7);
        strncpy(mg.m_msg,msg,strlen(msg));
        sendto(dfd,(char*)&mg,sizeof(mg),0,(struct sockaddr*)&dest,slen);
        printf("%s\n","私聊结束");
    }

    int getdfd() const{
        return dfd;
    }
    struct sockaddr_in& getdest(){
        return dest;
    }
};

int main(){
    clientChat cc("127.0.0.1",8888);
    cc.start();
    cc.ToALL("hello，world");
    message mg;
    strncpy(mg.fname,"uname",5);
    memset(mg.tname,0x00,8);
    strncpy(mg.m_msg,"hello",5);
    sendto(cc.getdfd(),(char*)&mg,sizeof(mg),0,(struct sockaddr*)&cc.getdest(),sizeof(cc.getdest()));
    sleep(2);
    char recvbuf[1040];
    memset(recvbuf,0x00,1040);
    recvfrom(cc.getdfd(),recvbuf,1040,0,NULL,NULL);
    printf("%s\n",recvbuf);
    cc.ToOne("lili","6666");
     sleep(2);
    memset(recvbuf,0x00,1040);
    recvfrom(cc.getdfd(),recvbuf,1040,0,NULL,NULL);
    printf("%s\n",recvbuf);
}
